﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;

// 动态编译*.cs源码为可执行文件
namespace EXE_macker
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0) CompileExecutable(args[0]);
            else
            {
                while (true)
                {
                    Console.WriteLine("请拖动*.cs源码文件至此，编译EXE\r\n");
                    string fileName = Console.ReadLine();
                    CompileExecutable(fileName);
                }
            }
        }

        // 从源码文件codeFile，编译生成EXE
        public static void CompileExecutable(String codeFile)
        {
            FileInfo source = new FileInfo(codeFile);
            if (source.Extension.ToUpper(CultureInfo.InvariantCulture) != ".CS")
            {
                Console.WriteLine("仅支持编译以.cs为拓展名的源码！");
                return;
            }
            String exeName = codeFile.Replace(".cs", ".exe").Replace(".CS", ".exe");

            // 设置编译参数
            CompilerParameters param = new CompilerParameters();
            param.ReferencedAssemblies.Add("System.dll");   // 添加系统程序集
            param.GenerateExecutable = true;                // 编译时生成可执行文件
            param.OutputAssembly = exeName;                 // 设置生成EXE的文件路径
            param.GenerateInMemory = false;
            param.TreatWarningsAsErrors = false;            

            // 从源码文件编译EXE
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults result = provider.CompileAssemblyFromFile(param, codeFile);

            if (result.Errors.Count > 0)
            {
                Console.WriteLine("编译出错：");
                foreach (CompilerError ce in result.Errors)
                    Console.WriteLine("  {0}", ce.ToString());
            }
            else Console.WriteLine("编译完成！生成{0}\r\n", result.PathToAssembly);
        }
    }
}
